#include "ibp_util.h"

int IsMatchString(char *pcMatchString, char *pcObjectString, char cMatchMuchCharacters, char cMatchOneCharacters)
{
	int el=strlen(pcMatchString);
	int sl=strlen(pcObjectString);
	char cs,ce;

	int is,ie;
	int last_xing_pos=-1;

	for(is=0,ie=0;is<sl && ie<el;){
		cs=pcObjectString[is];
		ce=pcMatchString[ie];

		if(cs!=ce){
			if(ce==cMatchMuchCharacters){
				last_xing_pos=ie;
				ie++;
			}else if(ce==cMatchOneCharacters){
				is++;
				ie++;
			}else if(last_xing_pos>=0){
				while(ie>last_xing_pos){
					ce=pcMatchString[ie];
					if(ce==cs)
						break;
					ie--;
				}

				if(ie==last_xing_pos)
					is++;
			}else
				return -1;
		}else{
			is++;
			ie++;
		}
	}

	if(pcObjectString[is]==0 && pcMatchString[ie]==0)
		return 0;

	if(pcMatchString[ie]==0)
		ie--;

	if(ie>=0){
		while(pcMatchString[ie])
			if(pcMatchString[ie++]!=cMatchMuchCharacters)
				return -2;
	} 

	return 0;
}

int nstoi( char *str , int len )
{
	char buf[ 20 + 1 ] ;
	
	memset( buf , 0x00 , sizeof(buf) );
	strncpy( buf , str , len );
	
	return atoi(buf);
}

char *strword( char *str , char *word )
{
	char	*copy = NULL ;
	char	*save = NULL ;
	char	*p = NULL ;
	
	copy = strdup( str ) ;
	if( copy == NULL )
		return NULL;
	
	p = strtok_r( copy , " \t" , & save ) ;
	while( p )
	{
		if( STRCMP( p , == , word ) )
		{
			p = p - copy + str ;
			free( copy );
			return p;
		}
		
		p = strtok_r( NULL , " \t" , & save ) ;
	}
	
	free( copy );
	return NULL;
}

char *gettok( char *str , const char *delim )
{
	static char	*copy = NULL ;
	static char	*save = NULL ;
	char		*p = NULL ;
	
	if( str )
	{
		if( copy )
		{
			free( copy );
			copy = NULL ;
			save = NULL ;
		}
		
		copy = strdup( str ) ;
		if( copy == NULL )
			return NULL;
		
		p = strtok_r( copy , delim , & save ) ;
		if( p == NULL )
		{
			free( copy );
			copy = NULL ;
			save = NULL ;
		}
		return p;
	}
	else
	{
		p = strtok_r( NULL , delim , & save ) ;
		if( p == NULL )
		{
			if( copy )
			{
				free( copy );
				copy = NULL ;
				save = NULL ;
			}
		}
		return p;
	}
}

char *strnchr( char *str , int c , int len )
{
	char		*p = NULL ;
	char		*p_end = str + len ;
	
	for( p = str ; p < p_end ; p++ )
	{
		if( (*p) == (char)c )
			return p;
	}
	
	return NULL;
}

char *strnstr( char *str , char *find , int len )
{
	char	*match = NULL ;
	int	offset ;
	
	for( offset = 0 ; (*str) && offset < len ; str++ , offset++ )
	{
		if( match == NULL )
		{
			if( (*str) == (*find) )
			{
				match = find + 1 ;
			}
		}
		else
		{
			if( (*str) == (*match) )
			{
				match++;
				if( (*match) == '\0' )
					return str - ( match - find ) + 1 ;
			}
			else
			{
				str -= ( match - find ) ;
				offset -= ( match - find ) ;
				match = NULL ;
			}
		}
	}
	
	return NULL;
}

